package com.zhanghe.study.thread;

/**
 * 同步解决线程安全问题
 *
 */
public class TestSynchronized {
    public static void main(String[] args) {
        WindowSynchronized runnable = new WindowSynchronized();
        Thread thread1 = new Thread(runnable,"窗口一");
        Thread thread2 = new Thread(runnable,"窗口二");
        Thread thread3 = new Thread(runnable,"窗口三");
        thread1.start();
        thread2.start();
        thread3.start();
    }

}

class WindowSynchronized implements Runnable{
    private int ticket = 100;
    @Override
    public void run() {
        while(true){
            synchronized (this){
                if(ticket > 0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"售票，票号"+ticket--);
                } else {
                    break;
                }
            }

        }
    }
}
